#!/usr/bin/php
<?php
/**
 * DolphinGTK - phpGtk framework
 *
 * @package    DolphinGTK
 * @author     Askarov Ruslan
 * @copyright  Askarov Ruslan (c) 2010.
 * @link       http://groups.google.com/group/dolphingtk
 * @license    http://www.opensource.org/licenses/gpl-license.php GPL
 * @version    0.1
 * @since      PHP v.: 5.2.1
 * @subpackage desktop
 * @category   make file
 * @filesource
 */


define('BASE_DIR', rtrim(str_replace('\\', '/', dirname(__FILE__)), '/'). '/');

if( !extension_loaded('bcompiler') ) {
  exit;
}

if( !empty($argv[1]) ) {
  @mkdir($argv[1],0755);
  if( !is_dir($argv[1]) ) {
    print "Нет директории для сборки!\n";
    exit;
  } else {
    $directory = $argv[1];
  }
} else {
  print "Введите директорию!\n";
  exit;
}

function bcompile( $file )
{
  $new_file = str_replace("php", "phb", $file);
  $fh = fopen($new_file, 'w');
  bcompiler_write_header($fh);
  bcompiler_write_file($fh, $file);
  bcompiler_write_footer($fh);
  fclose($fh);
}

function replace( $file )
{
  $new_file = str_replace("phb", "php", $file);

  if( file_exists($new_file) ) {
    unlink($new_file);
  }
  
  if( !rename($file, $new_file) ) {
    print "Не удалось переименовать файл '$file' в $new_file\n";
  }
}

function getFiles( $open_dir, $action )
{
  if( $action == 'compile' ) {
    $type = 'php';
  } else {
    $type = 'phb';
  }

  $dir = opendir( $open_dir );

  while( $file = readdir($dir) )
  {
    if( $file != '.' && $file != '..' && $file != 'make')
    {
      if( is_dir( $open_dir . $file ) )
      {
        getFiles( "$open_dir$file/", $action );
      }
      elseif( end(explode('.', $file)) == $type )
      {
        if( $action == 'compile') {
          bcompile( $open_dir.$file );
        } else {
          replace( $open_dir.$file );
        }
      }

    }
  }
  closedir($dir);
}


exec( 'cp -r ./ ' . $directory );
getFiles( $directory, 'compile' );
getFiles( $directory, 'replace' );
?>
